﻿using Approval.Domain;
using Contract.Domain;
using Contract.Infrastructure.Repository;
using Contract.WebApi.Application.Commands;
using MediatR;
using Newtonsoft.Json;
using PublicCommon;
using System.Collections.Generic;

namespace Contract.WebApi.Application.CommandHandler
{
    public class AddedContractCommandHandler : IRequestHandler<AddedContractCommands, int>
    {
        private readonly IRepository<Domain.Contract> repository;
        private readonly Cross_services_Helper cross_services_helper;
        private readonly IRepository<Tail> repository1;

        public AddedContractCommandHandler(IRepository<Domain.Contract> repository, Cross_services_Helper cross_services_helper, IRepository<Tail> repository1)
        {
            this.repository = repository;
            this.cross_services_helper = cross_services_helper;
            this.repository1 = repository1;
        }

        public async Task<int> Handle(AddedContractCommands request, CancellationToken cancellationToken)
        {
            var info = await repository.GetAsync(x => x.ContractNumber == request.ContractNumber);
            info.AuditState = request.AuditState;
            var ind = await repository.UpdateAsync(info);

            var obj = new HCTRelation();
            obj.HCTId = info.ContractNumber;
            obj.ApprovalId = 4;
            obj.ApprovalName = "小明";
            var message = await cross_services_helper.Post("http://10.31.60.9:8000/Approval/api/HCTRelation/HCTRelationAdd", obj);
            if (Convert.ToInt32(message) < 0)
            {
                return await Task.FromResult(-1);
            }

            var res = await cross_services_helper.Get($"http://10.31.60.9:8000/LongLine/api/LineInfo/GetLineRoute");
            var line = JsonConvert.DeserializeObject<List<LineDto>>(res);
            var inds = line.FirstOrDefault(x => x.Id == info.Route);
            Tail tail = new Tail();
            tail.ContractNumber = info.ContractNumber;
            tail.Shipping = inds.Address;
            tail.CreateDate = info.CreateDate;
            tail.ShipperEnterprise = info.ShipperEnterprise;
            tail.Responsible = info.Responsible;
            tail.TrackingState = "合同已创建";
            await repository1.AddAsync(tail);

            return ind;
        }
    }
}
